Reverse words¶
‘ ‘.join(S.split()[::-1])
Reverse words in a string.
def reverse_string_words(S):
for line in S.split('\n'):
# 1. separate each word
line_words = line.split()
# 2. reverse the word separated list
# line_words[-1::-1] here we have three arguments:
# * first is -1 that means start from last element, i.e.
# list[-1] equivalent to list[last]
# * second argument is empty that means move to end of list
# * third arguments is difference of steps
line_words = line_words[::-1]
# 3. join each word in string
return ' '.join(line_words)
print(reverse_string_words("The quick brown fox jumps over the lazy dog."))
print(reverse_string_words("Python Exercises."))
Output:
dog. lazy the over jumps fox brown quick The
Exercises. Python